from button import Button
from alien import Alien
from bullet import Bullet
from random import randint
from time import sleep
import sys
import pygame


def check_keydown_events(event, ship):
    """响应按键"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        ship.openfire = True
    elif event.key == pygame.K_q:
        sys.exit()


def check_keyup_events(event, ship):
    """响应松开"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False
    if event.key == pygame.K_SPACE:
        ship.openfire = False


def check_events(ai_settings, screen, stats, ship, play_button, aliens, bullets, game_runtime, sb):
    """响应按键和鼠标事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # 点击右上角 x 时关闭
            sys.exit()
        elif event.type == pygame.KEYDOWN:  # 键盘按下
            check_keydown_events(event, ship)
        elif event.type == pygame.KEYUP:  # 键盘松开
            check_keyup_events(event, ship)
        elif event.type == pygame.MOUSEBUTTONDOWN:  # 点击按钮区域
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings, screen, stats, ship, play_button, mouse_x, mouse_y, aliens, bullets, game_runtime, sb)


def check_play_button(ai_settings, screen, stats, ship, play_button, mouse_x, mouse_y, aliens, bullets, game_runtime, sb):
    """在玩家单击开始按钮时开始新游戏"""
    button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
    if button_clicked and not stats.game_active:
        # 隐藏光标
        pygame.mouse.set_visible(False)
        stats.rest_stats()
        sb.show_score
        print(stats.score)
        restart_game(ai_settings, stats, screen, ship, aliens, bullets, game_runtime)


def create_fleet(ai_settings, screen, aliens, game_runtime):
    """创建外星人部队"""
    # 删除出界的子弹
    for alien in aliens.copy():
        if alien.rect.top >= ai_settings.screen_height:
            aliens.remove(alien)
    # 每隔1s出现一个外星人
    game_runtime_tmp = game_runtime % 1000
    if game_runtime_tmp == 3:
        new_alien = Alien(ai_settings, screen)
        alien_x = randint(new_alien.rect.width, ai_settings.screen_width-new_alien.rect.width)
        new_alien.rect.x = float(alien_x)
        aliens.add(new_alien)
    # 外星人移动
    aliens.update()


def ship_hit(ai_settings, stats, screen, ship, aliens, bullets, game_runtime):
    """处理飞船和外星人碰撞"""
    if pygame.sprite.spritecollideany(ship, aliens):
        if stats.ships_left > 1:
            # 减少一条命
            stats.ships_left -= 1
            ships_left_msg = "船 x " + str(stats.ships_left)
            tmp_button = Button(ai_settings, screen, ships_left_msg)
            tmp_button.draw_button()
            pygame.display.flip()
            # 暂停
            sleep(1)
            restart_game(ai_settings, stats, screen, ship, aliens, bullets, game_runtime)
        else:
            stats.game_active = False
            # 隐藏光标
            pygame.mouse.set_visible(True)


def restart_game(ai_settings, stats, screen, ship, aliens, bullets, game_runtime):
    # 重置游戏统计信息
    # stats.rest_stats()
    stats.tmp_active = True
    stats.game_active = True
    # 清空外星人列表和子弹列表
    aliens.empty()
    bullets.empty()
    # 创建外星人舰队，并飞船居中
    create_fleet(ai_settings, screen, aliens, game_runtime)
    ship.center_ship()


def open_fire(ai_settings, screen, ship, bullets, game_runtime, aliens, sb, stats):
    """飞船开火"""
    # 子弹移动
    bullets.update()
    # 删除出界的子弹
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    # print(len(bullets))
    # 创建子弹精灵
    if ship.openfire:
        game_runtime_tmp = game_runtime % ai_settings.openfire_time
        if game_runtime_tmp <= 3:
            new_bullet = Bullet(ai_settings, screen, ship)
            bullets.add(new_bullet)
    # 检查是否有子弹击中了外星人
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
    if collisions:
        stats.score += ai_settings.alien_points
        sb.prep_score()


def update_screen(ai_settings, screen, stats, ship, aliens, bullets, play_button, sb):
    """更新屏幕上的图像"""
    # 每次循环时都重绘屏幕
    screen.fill(ai_settings.bg_color)
    # 绘制记分牌
    sb.show_score()
    # 绘制飞船
    ship.blitme()
    # 如果游戏处于非活动状态，就绘制开始按钮
    if not stats.game_active:
        play_button.draw_button()
    # 绘制外星人编组
    # for alien in aliens.sprites():
    #     alien.draw_bullet()
    aliens.draw(screen)
    # 绘制子弹编组
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    # 让最近绘制的屏幕可见（不断更新屏幕，显示元素的新位置，隐藏元素原来的位置）
    pygame.display.flip()
